package com.liu.stockmarket.ui.stock

import androidx.lifecycle.*
import com.liu.stockmarket.model.Diff
import com.liu.stockmarket.model.ResponseResult
import com.liu.stockmarket.model.HoldingStockProfit
import com.liu.stockmarket.repository.database.StockRepository
import com.liu.stockmarket.repository.database.TransactionRecordRepository
import com.liu.stockmarket.repository.database.entity.TransactionRecordEntity
import com.liu.stockmarket.repository.network.EasyMoneyRepository
import com.liu.stockmarket.utils.StockTransactionUtil
import com.liu.stockmarket.utils.diffToStockTransaction
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.math.BigDecimal

class StockViewModel(
    private val transactionRecordRepository: TransactionRecordRepository,
    private val stockRepository: StockRepository,
    private val easyMoneyRepository: EasyMoneyRepository
) : ViewModel() {


    private val _result = MutableLiveData<ResponseResult<HoldingStockProfit>>()
    val result: LiveData<ResponseResult<HoldingStockProfit>> = _result

    val allStockList = stockRepository.allStock.asLiveData()


    /**
     * @see result
     */
    fun getStockTransaction() {
        viewModelScope.launch(Dispatchers.IO) {
            val value = allStockList.value
            val stock = StockTransactionUtil.stock(easyMoneyRepository, transactionRecordRepository,value)

            _result.postValue(stock)
        }

    }

    fun deleteByStockId(stockId: Long) {
        viewModelScope.launch(Dispatchers.IO) {
            stockRepository.deleteStock(stockId)
        }

    }

    fun saveDividends(transactionRecordEntity: TransactionRecordEntity):Boolean {
        viewModelScope.launch {
            transactionRecordRepository.save(transactionRecordEntity)
        }
        return true
    }

    fun save(stockId: Long, holdingPrice: BigDecimal, holdingNumber: BigDecimal) {
        viewModelScope.launch(Dispatchers.IO) {
            stockRepository.modifyHoldingPriceAndNumber(stockId, holdingPrice, holdingNumber)
            _result.postValue(ResponseResult.success())
        }

    }



    class StockViewModelFactory(
        private val transactionRecordRepository: TransactionRecordRepository,
        private val stockRepository: StockRepository,
        private val easyMoneyRepository: EasyMoneyRepository
    ) :
        ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            @Suppress("UNCHECKED_CAST")
            return StockViewModel(
                transactionRecordRepository,
                stockRepository,
                easyMoneyRepository
            ) as T
        }

    }
}